package com.ckjava.test.service;

import com.ckjava.test.properties.DbProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;

@Service
public class AsyncService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private DbProperties dbProperties;

    public String getDbProperties() {
        return dbProperties.toString();
    }

    @Async
    public void asyncData(String param) {
        /*try {
            //Thread.sleep(1);
        } catch (InterruptedException e) {
            e.toString();
        }*/

        logger.info("Execute method asynchronously, thread name = {}, param = {}", Thread.currentThread().getName(), param);
        throw new RuntimeException("异常");
    }

    /*@Async("selfConfigThreadPool")
    public void asyncSelfData() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.toString();
        }
        logger.info("Execute method asynchronously, thread name = {}", Thread.currentThread().getName());
    }
*/
    @Async
    public Future<String> asyncGetData() {
        logger.info("Execute method asynchronously, thread name = {}", Thread.currentThread().getName());
        try {
            Thread.sleep(2000);
            AsyncResult asyncResult = new AsyncResult("true");
            asyncResult.addCallback(data -> logger.info("success,result = {}", data), ex -> logger.error("异常", ex));

            return asyncResult;
        } catch (Exception e) {
            logger.error("");
            return new AsyncResult(null);
        }
    }
}
